#include <avr/io.h>
#include <stdbool.h>		//for boolean
#include <avr/io.h>			//i/o register definitions
#include <avr/interrupt.h>	//interrupt definitions
#include <stdint.h>			//for uint types
#include <stdlib.h>			//for rand
#include <stdbool.h>		//for boolean


#define BUFFER_LENGTH 40

volatile char recieveBuffer[BUFFER_LENGTH] = {0};
volatile uint8_t recieveBufferCount;
volatile uint8_t recieveCount = 0;
volatile uint8_t recieveLength = 0;
volatile bool first;
volatile bool display;

void initRecieve()
{
	DDRD &= ~((1<<PD6) | (1<<PD3));//Sets the ICP1 to be an input
	recieveCount = 0;
	recieveLength = 0;
	recieveBufferCount = 0;
	first =true;
	display = false;
	
	MCUCR = (1<<ISC11)|(1<<ISC10);		//Begin listening for a Rising Edge
	GICR = (1<<INT1); 					//Enable INT1 interrupts
	TIMSK |= (1<<OCIE0);				//enable timer0 interrupt
	
	TCCR0 = (1<<WGM01); //CTC MODE
	OCR0 = 26; //104us, 1/4 bit interval
	
	sei();	
}

void displayBuffer()
{
		volatile int i = 0;
		for(i = 0; i < recieveBufferCount; ++i)
		{
			char c = (recieveBuffer[i]);
			printf("%c", c);
		}
		recieveBufferCount = 0;
		recieveCount = 0;

}

ISR(TIMER0_COMP_vect){
	if(first){
		first = false;
		OCR0 = 104; // 416us next match
	}
	
	//if(recieveBufferCount < recieveLength)
	//{
		uint8_t data = PIND;
		data = (data>>PD6)&(0x01);
		recieveBuffer[recieveBufferCount] = (recieveBuffer[recieveBufferCount]<<1)|data;
		recieveCount++;
		//Recieve stuff
		if(recieveCount >= 8)
		{
			first = true;
			TCCR0 &= ~((1<<CS01)|(1<<CS00)); // set first, disable timer
			recieveCount = 0;
			char c = (recieveBuffer[recieveBufferCount])&(0x7F);
			recieveBuffer[recieveBufferCount] = c;
			recieveBufferCount++;
			//display = true;
			if((c == '\n') || (c == '\r'))
			{
				displayBuffer();
			}
			//displayBuffer();
		}
	//}
}

ISR(INT1_vect)
{
	TCCR0 |= (1<<CS01)|(1<<CS00); // clk/64 start timer
	if(first){
		OCR0 = 26; // 104us, 1/4 bit interval
	}
}